<?php

namespace app\modules\backend\controllers;

use app\filters\auth\HttpBearerAuth;
use app\models\Base;
use app\models\User;
use app\models\Admin;
use app\tools\Re;
use app\tools\Rongyun;
use yii\helpers\Inflector;
use Yii;
use yii\web\UnauthorizedHttpException;
use app\models\Identity;
use yii\filters\AccessControl;
use yii\web\ForbiddenHttpException;
date_default_timezone_set('PRC');
header('Access-Control-Allow-Origin: *');

/**
 * Default controller for the `admin` module
 */
class BaseController extends \app\controllers\BaseController
{

    public function behaviors(){
        $behaviors = parent::behaviors();
        if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
            $behaviors['authenticator'] = [
                'class' => HttpBearerAuth::class
            ];
        }
        return $behaviors;
    }

    /**
     * @param $action
     * @return bool
     * @throws UnauthorizedHttpException
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        if(parent::beforeAction($action)){
            // if(
            //     !Yii::$app->user->isGuest &&
            //     Yii::$app->user->identity->type != User::ADMIN &&
            //     (!in_array($this->action->id, ['virtual-user-list', 'select-data']))
            // ){
            //     throw new UnauthorizedHttpException('您无权限登录此后台！');
            // }
            return true;
        }else{
            return false;
        }
    }

    /**
     * @param Base|string $model_name
     * @param int $id
     * @param array $data
     * @return mixed
     */
    public function edit($model_name, $id = 0, $data = [], $model_type = 0){

        if($id){
            $model = $model_name::findOne($id);
            if(!$model){
                return Re::data(null, '您修改的数据不存在', Re::ERROR);
            }
        }else{
            $model = new $model_name();
        }

        $model->load($data, '');

        if($model->save()){
            if ($model_type == 1 && !$id) {//创建直播间，创建融云聊天室、创建系统公告的用户信息、创建发送问答库信息用户
              Rongyun::createRyChatRoom($model);
              Admin::createUser($model->id, '系统消息', 3);
              Admin::createUser($model->id, '问答库', 4);
            }
            $re_data = [];
            foreach ($data as $k=>$v) {
                $method_name = 'show'.Inflector::camelize($k);
                if(method_exists($model, $method_name)){
                    $re_data[$k] = $model->$method_name();
                }elseif(array_key_exists($k, $model->attributes)){
                    $re_data[$k] = $model->$k;
                }else{
                    $re_data[$k] = $v;
                }
            }
            $re_data['id'] = $model->id;
            return Re::data(['data'=>$re_data]);
        }else{
            return Re::data(null, $model->showErrors(), Re::ERROR);
        }
    }

    /**
     * 获取资讯信息
     */
    public function getArticeInfo($aid){
        //$url = "https://www.weijiaju.net/article/view?id=".$aid;
        $url = Yii::$app->params['domain'] . "/article/view-jmb?id=".$aid;
        $method = "GET";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $result_data = json_decode(curl_exec($curl));
        return $result_data;
    }

    /**
     * 获取资讯列表
     */
    public function getArticleAddList($keyword=''){
        //$url = "https://www.weijiaju.net/article/view?id=".$aid;
        $url = Yii::$app->params['domain'] . "/article/article-add-list?keyword=".$keyword;
        $method = "GET";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        //var_dump(curl_exec($curl));die;
        $result_data = json_decode(curl_exec($curl));
        //var_dump($result_data);die;
        return $result_data;
    }

    /**
     * 获取地址经纬度
    */
    public function getGeocode($address_info){
        $method = "GET";
        $url = 'http://restapi.amap.com/v3/geocode/geo?key=d91c1a89a746f4da1d732a3364a7d522&address='.$address_info;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        $result_data = json_decode(curl_exec($curl));
        $location = $result_data->geocodes[0]->location;
        $lat = '0.00';
        $lng = '0.00';
        if (!empty($location)) {
            $location_arr = explode(',', $location);
            $lng = $location_arr[0];
            $lat = $location_arr[1];
        }
        $arr = [];
        array_push($arr, $lat,$lng);
        return $arr;
    }
}
